package com.banciyuan.bcywebview.biz.goods.order.myorder;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.goods.store.AllGoodsActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.OrderItem;


public class MyOrderActivity extends BaseActivity implements View.OnClickListener {
    private PullToRefreshListView mRefreshView;
    private ListView mListView;
    private RequestQueue mQueue;
    private MyOrderAdapter myOrderAdapter;
    private int page = 1;
    private List<OrderItem> mOrderItemList = new ArrayList<>();
    private boolean loading = false;
    private boolean end_flag = false;
    private View orderEmptyView;
    private ProgressbarHelper mProgressbarHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myorder_layout);
        initArgs();
        initActionbar();
        initUi();
        initProgressbar();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                page = 1;
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, findViewById(R.id.base_action_bar));
        mActionbarHelper.setTitle(getString(R.string.my_order));
    }

    @Override
    protected void initUi() {
        orderEmptyView = findViewById(R.id.order_emptyview);
        ((TextView) findViewById(R.id.tv_desc_one)).setText(getString(R.string.no_purchased_order));
        ((ImageView)findViewById(R.id.iv_empty_pic)).setImageResource(R.drawable.ic_empty_order);
        mRefreshView = (PullToRefreshListView) findViewById(R.id.listview);
        mListView = mRefreshView.getRefreshableView();

        Calendar end = Calendar.getInstance();
        end.set(Calendar.YEAR, 2017);
        end.set(Calendar.MONTH, 1);
        end.set(Calendar.DATE, 18);
        end.set(Calendar.HOUR, 0);

        Calendar start = Calendar.getInstance();
        start.set(Calendar.YEAR, 2017);
        start.set(Calendar.MONTH, 0);
        start.set(Calendar.DATE, 13);
        start.set(Calendar.HOUR, 0);
        Calendar now = Calendar.getInstance();
        if (now.before(end) && now.after(start)) {
            mListView.addHeaderView(View.inflate(this, R.layout.spring_warn, null));
        }

    }

    @Override
    protected void initAction() {
        mRefreshView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && !end_flag) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        mRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });
        findViewById(R.id.tv_go_order_acg).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.PAGE, String.valueOf(page)));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + ZhipinApi.getlistBought();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, MyOrderActivity.this)) {
                        JSONObject jsonObject = new JSONObject(s);
                        List<OrderItem> tempList = new Gson().fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<OrderItem>>() {
                        }.getType());
                        if (page == 1 && tempList.isEmpty()) {
                            orderEmptyView.setVisibility(View.VISIBLE);
                        } else {
                            orderEmptyView.setVisibility(View.GONE);
                            processData(tempList);
                        }
                        mProgressbarHelper.onSuccess();
                        mRefreshView.onRefreshComplete();
                        loading = false;
                    } else {
                        onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onError();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void onError() {
        mProgressbarHelper.onFailed();
        mRefreshView.onRefreshComplete();
        loading = false;
    }

    private void processData(List<OrderItem> tempList) {
        if (page == 1)
            mOrderItemList.clear();
        mOrderItemList.addAll(tempList);
        if (null == myOrderAdapter) {
            myOrderAdapter = new MyOrderAdapter(this, mOrderItemList);
            mListView.setAdapter(myOrderAdapter);
        } else {
            myOrderAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_order_acg:
                gotoUtil.gotoAct(this, AllGoodsActivity.class);
                break;
        }
    }
}
